// 列表源数据
let arr = [
    { id: 'i1', type: 'type1', age: 'a1', num1: 1, num2: 1 ,num3: 4}, // 1
    { id: 'i2', type: 'type2', age: 'a1', num1: 2, num2: 1 ,num3: 4}, // 2
    { id: 'i1', type: 'type1', age: 'a2', num1: 2, num2: 1 ,num3: 4}, // 3
    { id: 'i1', type: 'type3', age: 'a1', num1: 2, num2: 3 ,num3: 4}, // 1
    { id: 'i1', type: 'type2', age: 'a2', num1: 2, num2: 3 ,num3: 4}, // 3
    { id: 'i2', type: 'type2', age: 'a1', num1: 2, num2: 3 ,num3: 4}, // 2
]

// 表头
let tabelHead = [
    {title: '年龄',field:'age'},
    {title: 'id',field:'id'},
]

let keyMap = { // 动态新增表头映射
    type1: 'num1',
    type2: 'num2',
    type3: 'num3',
    type4: 'num4'
}
let filterHeadFn = (arr) => { // 过滤头部，用于动态添加头部
    let tempField = []
    arr.forEach((item) => {
        tempField.push(item.type)
    })
    tempField = [...new Set(tempField)]
    let addHeadArr = tempField.map((itemField,index) => {
        return {
            title: itemField,
            field: `product${index}`,
            isProduct: true,
        }
    })
    return addHeadArr
}
let addHeadArr = filterHeadFn(arr,tabelHead)
tabelHead = [...tabelHead,...addHeadArr]
// 设置列表数据
let setTableDataFn = (addHeadArr,arr) => {
    addHeadArr.forEach((itemHead) => {
        arr.forEach(itemData => {
            itemData[itemHead.field] =itemData[keyMap[itemHead.title]] 
        })
    })
}
setTableDataFn(addHeadArr,arr)
console.log(arr);
console.log(tabelHead);

// 合并数据
let mergeTableFn = (arr,addHeadArr) => {
    let fieldFilterArr = ['id','age','type']
    let exitFn = (itemData,newItem) => {
       let flag = fieldFilterArr.every(itemField => itemData[itemField] === newItem[itemField])
       return flag
    }
    let newTableArr = []
    arr.forEach(itemData => {
        if (!newTableArr.length) {
            newTableArr.push(itemData)
            return
        }
        
        for (let indexNew = 0; indexNew < newTableArr.length; indexNew++) {
            if (exitFn(itemData,newTableArr[indexNew])) {
                addHeadArr.forEach(itemHead => {
                    newTableArr[indexNew][itemHead.field] += itemData[itemHead.field]
                })
                break
            }else {
                if (!exitFn(itemData,newTableArr[indexNew]) && indexNew < newTableArr.length - 1) {
                    continue
                }else {
                    newTableArr.push(itemData)
                    break
                }
            }
        }
    })
    return newTableArr
}
let newTableArr = mergeTableFn(arr,addHeadArr)
console.log('newTableArr =>',newTableArr);








